# -*- coding: utf-8 -*-


from contextlib import closing
import werkzeug.urls
import urllib
import simplejson

import openerp
from openerp.http import request
from openerp.osv import orm

SUPERUSER_ID = 1

#拦截所有HTTP请求，检查是否有微信回调验证参数
#有验证参数的话则进行验证，验证后跳转到业务页面
class ir_http(orm.AbstractModel):
    _inherit = 'ir.http'

    #微信验证
    def weixin_auth(self, code, state):
        #自定义菜单中无法用大括号{}符号，用小括号()代替，需要替换
        state = state.replace("'", '"')
        state = state.replace('(', '{')
        state = state.replace(')', '}')
        if state[0] != '{':
            state = '{' + state + '}'
        try:
            state = simplejson.loads(state)
        except(Exception), e:
            raise Exception('------------------ weixin state not json: %s' % state)
            return

        httprequest = request.httprequest
        dbname = state.get('db') or httprequest.session.db
        if not dbname:
            raise Exception("no dbname!")

        context = state.get('c', {})
        provider = 'weixin'

        kw = httprequest.args.to_dict()
        kw.update(state)
        credentials = self.pool['res.users'].auth_oauth(request.cr, SUPERUSER_ID, provider, kw, context=context)
        httprequest.session.oauth_uid = credentials['oauth_uid']
        httprequest.session.oauth_access_token = credentials['oauth_access_token']
        httprequest.session.oauth_provider_id = credentials['oauth_provider_id']
        httprequest.session.weixin_id = credentials['weixin_id']
        print '----------- credentials:', credentials
        uid = ''
        #如果没有返回login_id，说明账号没有绑定
        if credentials['login_id']:
            uid = httprequest.session.authenticate(credentials['dbname'], credentials['login_id'],
                                                       credentials['oauth_access_token'])
        return uid, state

    #重载url分发
    def _dispatch(self):
        args = request.httprequest.args
        code = args.get('code')
        state = args.get('state')
        if code and state:
            uid, state_params = self.weixin_auth(code, state)
            kw = request.httprequest.args.to_dict()
            del kw['code']
            del kw['state']
            if state_params:
                kw.update(state_params)
            #如果登录成功
            if uid:
                return werkzeug.utils.redirect(request.httprequest.path + '?' + urllib.urlencode(kw))
            else:
                #没有登录成功，说明没有绑定账号，跳转到绑定页面
                return werkzeug.utils.redirect("http://" + request.httprequest.host + "/weixin/binding" +
                                               '?' + urllib.urlencode(kw))
        return super(ir_http, self)._dispatch()